package alipay;

import cn.com.ejiakanghu.web.alimini.AliMiniConfig;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradeCreateRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.api.response.AlipayTradeCreateResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * @author houzb
 * @Description
 * @create 2021-04-09 23:46
 */
public class AliPayTool {
    private Logger logger = LoggerFactory.getLogger(AliPayTool.class);

     /**
     * 阿里app支付调用
     * @param orderCode
     * @param totalFee
     * @param title
     * @param content
     * @param isFacePay 是否可以支持面对面付款,为空则不支持,非空则根据配置进行设置
     * @return
     */
    private Map<String,String> aliPayAccess(String orderCode, String totalFee, String title, String content, Integer isFacePay, long uid, Object aliBuyerId) {
        Map<String,String> result = new HashMap<String, String>();
        /*if(isFacePay != null && isFacePay != 0) {
            //根据配置进行选择的支付方式
            SystemConfig systemConfig = configService.getConfigByKey("ALI_PAY_TYPE_CONFIG");
            if (systemConfig != null) {
                String configVal = systemConfig.getConfigvalue();
                Map<String, Object> configMap = JacksonUtil.gson.fromJson(configVal, Map.class);
                Object payType = configMap.get("pay_type");
                List<Double> list = (List<Double>) configMap.get("limit");
                boolean flg = list.size() == 0 || list.contains(Double.parseDouble(uid + ""));
                if ("face".equals(payType) && flg) {
                    String orderStr = aliPayFaceAccess(orderCode, totalFee, title,aliBuyerId);
                    result.put("payType", "face");
                    result.put("order", orderStr);
                    return result;
                }
            }
        }*/
        String orderStr = aliPayAppAccess(orderCode, totalFee, title, content);
        result.put("payType","app");
        result.put("order",orderStr);
        return result;
    }

    /**
     * 阿里app支付调用
     * @param orderCode
     * @param totalFee
     * @param title
     * @param content
     * @return
     */
    private String aliPayAppAccess(String orderCode, String totalFee, String title, String content) {
        //实例化客户端
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", AliMiniConfig.ALI_MINI_APP_ID, AliMiniConfig.ALI_PRIVATE_KEY, "json", "utf-8", AliMiniConfig.ALI_PUBLIC_KEY, "RSA2");
//实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
//SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setBody(content);
        model.setSubject(title);
        model.setOutTradeNo(orderCode);
        model.setTimeoutExpress("30m");
        model.setTotalAmount(totalFee);
        model.setProductCode("QUICK_MSECURITY_PAY");
        request.setBizModel(model);
        request.setNotifyUrl("https://ejiakanghu.com.cn/ali_pay/callback");
        try {
            //这里和普通的接口调用不同，使用的是sdkExecute
            AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
            return response.getBody();//就是orderString 可以直接给客户端请求，无需再做处理。
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 当面付阿里调用
     * @param orderCode
     * @param totalFee
     * @param title
     * @return
     */
    private String aliPayFaceAccess(String orderCode, String totalFee, String title,Object buyerId) {
        if(buyerId == null) {
            logger.error("ali face access err {},{}",orderCode,title);
            return null;
        }
        //实例化客户端
        AlipayClient alipayClient = new 	DefaultAlipayClient("https://openapi.alipay.com/gateway.do", AliMiniConfig.ALI_MINI_APP_ID, AliMiniConfig.ALI_PRIVATE_KEY, "json", "utf-8",  AliMiniConfig.ALI_PUBLIC_KEY, "RSA2");
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.create.
        AlipayTradeCreateRequest request = new AlipayTradeCreateRequest();
        request.setNotifyUrl("https://ejiakanghu.com.cn/ali_pay/callback");
        //SDK已经封装掉了公共参数，这里只需要传入业务参数。
        request.setBizContent("{" +
                "\"out_trade_no\":\""+orderCode+"\"," +
                "\"total_amount\":"+totalFee+"," +
                "\"subject\":\""+title+"\"," +
                "\"buyer_id\":\""+buyerId+"\"" +
                "}");
        try {
            //使用的是execute
            AlipayTradeCreateResponse response = alipayClient.execute(request);
            String trade_no = response.getTradeNo();//获取返回的tradeNO。
            return trade_no;
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return null;
    }
}
